const gulp = require("gulp")
const cssmin = require("gulp-cssmin")
const autoPreFixer = require("gulp-autoprefixer")
const less = require("gulp-less")
const uglify = require("gulp-uglify")
const babel = require("gulp-babel")
const htmlmin = require("gulp-htmlmin")
const imgmin = require("gulp-imagemin")
const clean = require("gulp-clean")
const connect = require("gulp-connect")
const options = {
    collapseBooleanAttributes:true,
    collapseWhitespace:true,
    minifyCSS:true,
    removeAttributeQuotes:true,
    removeComments:true,
    removeEmptyAttributes:true
}
// 处理 样式
gulp.task("style",()=>{
    return gulp.src("./src/less/*.less")
    .pipe(less())
    .pipe(autoPreFixer())
    .pipe(cssmin())
    .pipe(gulp.dest("./dist/css"))
	.pipe(connect.reload())
})
// 处理js
gulp.task("js",()=>{
    return gulp.src("./src/js/*.js")
    .pipe(babel({
        presets:['@babel/env']
    }))
    .pipe(uglify())
    .pipe(gulp.dest("./dist/js/"))
	.pipe(connect.reload());
})

// 处理html
gulp.task('html',()=>{
    return gulp.src("./src/pages/*.html")
    .pipe(htmlmin(options))
    .pipe(gulp.dest("./dist/pages/"))
	.pipe(connect.reload());
})
gulp.task("clean",()=>{
	return gulp.src("./dist/**/")
	.pipe(clean())
})
// 压缩图片
gulp.task('img',()=>{
	return gulp.src("./src/images/**/*")
	.pipe(imgmin())
	.pipe(gulp.dest("./dist/images/"))
	.pipe(connect.reload());
})

// build 任务  同时执行多个任务 (同步(有先后顺序),异步(同时进行))
/* 
 gulp.series("任务1","任务2","任务3")
 */
/* gulp.task("build",gulp.series("html","style","js","img")); */

/* 
gulp.parallel()  异步的任务 
 */

gulp.task("watch",()=>{
	gulp.watch("./src/pages/*.html",gulp.series("html"));
	gulp.watch("./src/less/*.less",gulp.series("style"))
	gulp.watch("./src/js/*.js",gulp.series("js"))
	gulp.watch("./src/images/*",gulp.series("img"))
})

// 开启服务器
gulp.task("dev",()=>{
	connect.server({
		root:"dist",
		livereload:true,
        port:9530,
        directoryListing: false
	});
})
// connect.reload()  重启服务器 
// build
gulp.task("build",gulp.series("clean",gulp.parallel("html","style","js","img")));

// task的名字如果为 default 命令行执行 gulp 自动执行 default
gulp.task("default",gulp.series("build",gulp.parallel("watch","dev")))

